<template>
  <div class="box-wrapper">
    <div class="title">基础配置 <span class="tips text">当前剩余使用次数{{interest}}次</span></div>
    <el-form ref="form" :model="params" :rules="rules" label-width="120px" size="small">
      <el-form-item label="可用油站: " prop="gasId">
        <el-select placeholder="请选择可用油站" clearable v-model="params.gasId" @change="searchGasApi">
          <el-option v-for="item in gasList" :key="item.gasId" :label="item.gasName" :value="item.gasId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动名称: " prop="activeName">
        <el-input placeholder="请输入活动名称" clearable v-model="params.activeName" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="活动有效期: " prop="date">
        <el-date-picker v-model="params.date" type="datetimerange" @blur="selectDate=''" :editable="false" clearable unlink-panels value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="券领取规则: ">
        <span>该活动每人每天每种优惠券仅领取1次</span>
      </el-form-item>
      <el-form-item label="券使用规则: ">
        <span>每笔订单仅可使用1张优惠券</span>
      </el-form-item>
    </el-form>
    <div class="title">优惠券配置 <span class="text">最多添加6种优惠券</span></div>
    <div class="title">
      <img src="../../assets/image/add-coupon.png" alt="" @click="showSelectCoupon">
    </div>
    <div class="coupon-box">
      <span v-if="!selectedCoupon.length" style="font-size: 14px">请配置优惠券</span>
      <couponTemplate v-for="(item, index) in selectedCoupon" :key="index" :coupon="item" :currGasName="currGasName" @edit="editAddCoupon(item)" @delete="deleteCoupon(item)"></couponTemplate>
    </div>
    <div class="btns">
      <el-button size="small" type="primary" @click="save" :disabled="saveDisabled">确定</el-button>
    </div>
    <!-- 编辑优惠券 -->
    <el-dialog :visible.sync="isShowEditAddCoupon" :title="couponParams.onlyId ? '编辑优惠券':'新增优惠券'" width="600px">
      <el-form label-width="140px" size="small" ref="couponForm" :model="couponParams" :rules="couponRules">
        <el-form-item label="优惠券名称: " prop="couponTitle">
          <el-input v-model="couponParams.couponTitle" placeholder="请输入优惠券名称" clearable maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="优惠券面额: " prop="couponMoney">
          <el-input v-model="couponParams.couponMoney" :placeholder="getPlaceholder(1)" clearable></el-input>
        </el-form-item>
        <el-form-item label="使用门槛: " prop="couponConditionMoney">
          <el-input v-model="couponParams.couponConditionMoney" :placeholder="getPlaceholder(2)" clearable>
            <template slot="prepend">加油满</template>
            <template slot="append">元可使用</template>
          </el-input>
        </el-form-item>
        <el-form-item label="券有效期: " prop="expireDateInterval">
          <el-input v-model="couponParams.expireDateInterval" :placeholder="getPlaceholder(3)" clearable>
            <template slot="prepend">发券后</template>
            <template slot="append">天内有效</template>
          </el-input>
        </el-form-item>
        <el-form-item label="可用油品: " prop="oils">
          <el-checkbox-group v-model="couponParams.oils" @change="handelCheck">
            <el-checkbox label="全部油品"></el-checkbox>
            <el-checkbox v-for="item in oilTypeList" :label="`${item.id}`" :key="item.id" :disabled="checkDisabled">{{item.oilNum}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="每天赠送张数限制: " prop="numberLimit">
          <el-radio-group v-model="couponParams.numberLimit" class="input-radio" @change="$set(couponParams, 'number', '')">
            <el-radio :label="false">不限制</el-radio>
            <el-radio :label="true">
              <el-input :placeholder="getPlaceholder(4)" v-model="couponParams.number" :disabled="!couponParams.numberLimit">
                <template slot="append">张</template>
              </el-input>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="dialog-btns" slot="footer">
        <el-button size="small" @click="isShowEditAddCoupon = false">取消</el-button>
        <el-button size="small" type="primary" @click="saveCoupon">确定</el-button>
      </div>
    </el-dialog>
    <!-- 选择优惠券 -->
    <el-dialog :visible.sync="isShowSelectCoupon" title="选择优惠券" width="870px">
      <div class="dialog-header" slot="title">
        <img src="./../../assets/image/add-custom.png" alt="" @click="editAddCoupon()" v-if="couponList.length < 12">
        <div>
          <span>请选择优惠券</span> <span>一次最多勾选添加6张优惠券</span>
        </div>
      </div>
      <div class="coupon-box">
        <couponTemplate v-for="(item, index) in couponList" :key="index" :coupon="item" :currGasName="currGasName" @select="selectCoupon(item)" @edit="editAddCoupon(item, 'template')" @delete="deleteCoupon(item, 'template')"></couponTemplate>
      </div>
      <div class="dialog-btns" slot="footer">
        <el-button size="small" @click="isShowSelectCoupon = false">取消</el-button>
        <el-button size="small" type="primary" @click="saveSelectedCoupon">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import couponTemplate from './components/couponTemplate'
import {
  getAllGasInfoList,
  searchGas,
  getStoreCouponActiveDetail,
  createStoreCouponActive,
  updateStoreCouponActive,
  getCouponTemplate,
  getCouponLimit,
  queryInterest,
  getDisabledDate
} from '@api/market'

export default {
  components: {
    couponTemplate
  },
  data () {
    const couponMoney = (rule, value, callback) => {
      const { amount = {} } = this.couponRulesLimt
      if (value < amount.min || value > amount.max) {
        return callback(new Error(`请输入${amount.min}-${amount.max}范围正整数`))
      }
      if (this.couponParams.couponConditionMoney) this.$refs.couponForm.validateField('couponConditionMoney')
      callback()
    }
    const couponConditionMoney = (rule, value, callback) => {
      const { couponMoney } = this.couponParams
      if (!couponMoney) {
        return callback(new Error('请先输入优惠券面额'))
      }
      const { condition = {}, multiple = {} } = this.couponRulesLimt
      if (value < couponMoney * multiple.max) {
        return callback(new Error(`使用门槛金额需是优惠券面额${multiple.max}倍以上`))
      }
      if (value < condition.min || value > condition.max) {
        return callback(new Error(`请输入${condition.min}-${condition.max}范围正整数`))
      }
      callback()
    }
    const expireDateInterval = (rule, value, callback) => {
      const { expire = {} } = this.couponRulesLimt
      if (value < expire.min || value > expire.max) {
        return callback(new Error(`请输入${expire.min}-${expire.max}范围正整数`))
      }
      callback()
    }
    const numberLimit = (rule, value, callback) => {
      const { number: numberLimt } = this.couponParams
      const { number = {} } = this.couponRulesLimt
      if (value) {
        if (!numberLimt) {
          return callback(new Error('请输入每天赠送张数限制'))
        }
        if (!/(^[1-9]\d*$)/.test(numberLimt)) {
          return callback(new Error('请输入正整数'))
        }
        if (numberLimt < number.min || numberLimt > number.max) {
          return callback(new Error(`请输入${number.min}-${number.max}范围正整数`))
        }
      }
      callback()
    }
    return {
      params: {},
      rules: {
        gasId: { required: true, message: '请选择油站', trigger: 'change' },
        activeName: { required: true, message: '请输入活动名称', trigger: 'change' },
        date: { required: true, message: '请选择活动有效期', trigger: 'change' }
      },
      checkDisabled: false,
      saveDisabled: false,
      interest: 0,
      upGasId: '',
      disabledDate: [],
      // 编辑/新增优惠券
      isShowEditAddCoupon: false,
      couponParams: {},
      couponRulesLimt: {},
      couponRules: {
        couponTitle: { required: true, message: '请输入优惠券名称', trigger: 'change' },
        couponMoney: [
          { required: true, message: '请输入优惠券面额', trigger: 'change' },
          { pattern: /(^[1-9]\d*$)/, message: '请输入正整数', trigger: 'change' },
          { validator: couponMoney, trigger: 'change' }
        ],
        couponConditionMoney: [
          { required: true, message: '请输入使用门槛', trigger: 'change' },
          { pattern: /(^[1-9]\d*$)/, message: '请输入正整数', trigger: 'change' },
          { validator: couponConditionMoney, trigger: 'change' }
        ],
        expireDateInterval: [
          { required: true, message: '请输入券有效期', trigger: 'change' },
          { pattern: /(^[1-9]\d*$)/, message: '请输入正整数', trigger: 'change' },
          { validator: expireDateInterval, trigger: 'change' }
        ],
        oils: { required: true, message: '请选择可用油品', trigger: 'change' },
        numberLimit: [
          { required: true, message: '请选择每天赠送张数限制', trigger: 'change' },
          { validator: numberLimit, trigger: 'change' }
        ]
      },
      // 选择优惠券
      isShowSelectCoupon: false,
      // 可选优惠券列表
      couponList: [],
      selectedCoupon: [],
      // 油站、油号
      gasList: [],
      oilTypeList: [],
      currGasName: ''
    }
  },
  computed: {
    pickerOptions () {
      const { duration = {} } = this.couponRulesLimt
      return {
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime()
          if (maxDate) {
            this.selectDate = ''
          }
        },
        disabledDate: (time) => {
          const currTime = moment().format('YYYY-MM-DD')
          const date = moment(time).format('YYYY-MM-DD')
          if (this.selectDate) {
            const maxTime = moment(this.selectDate).add(duration.max, 'days').format('YYYY-MM-DD')
            const minTime = moment(this.selectDate).subtract(duration.max, 'days').format('YYYY-MM-DD')
            return moment(date).isBefore(minTime) || moment(date).isBefore(currTime) || moment(date).isAfter(maxTime) || this.disabledDate.includes(date)
          } else {
            return moment(date).isBefore(currTime) || this.disabledDate.includes(date)
          }
        }
      }
    }
  },
  mounted () {
    this.getCouponLimit()
    this.getCouponTemplate()
    const { activeId, gasId } = this.$route.query
    if (activeId) {
      return this.getDetail(activeId)
    }
    if (gasId) {
      this.$set(this.params, 'gasId', gasId)
    }
    this.getAllGasStationsApi()
  },
  methods: {
    async getDetail (activeId) {
      const { code, result = {} } = await getStoreCouponActiveDetail({ activeId })
      if (code !== 200) return
      this.selectedCoupon = result.couponList
      this.selectedCoupon.forEach((item, index) => {
        if (!item.oils) {
          item.oilNames = '全部油品'
          item.oils = ['全部油品']
        } else {
          item.oils = item.oils.split(',')
        }
        item.number = item.number || ''
        item.onlyId = Date.now() + index
        item.isCanEdit = true
        item.noSelect = true
      })
      result.date = [result.startTime, result.endTime]
      delete result.couponList
      this.params = result
      this.getAllGasStationsApi()
    },
    save () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (!this.selectedCoupon.length) return this.$message.warning('请选择优惠券')
        try {
          const couponListJson = JSON.stringify(this.selectedCoupon.map(item => {
            let { couponTitle, couponMoney, couponConditionMoney, expireDateInterval, oils, numberLimit, number } = item
            oils = oils.map(oil => {
              return oil.split('-')[0]
            })
            return { couponTitle, couponMoney, couponConditionMoney, expireDateInterval, oils: oils.includes('全部油品') ? '' : oils.join(','), numberLimit, number }
          }))
          const { gasId, activeName, date, activeId = '' } = this.params
          const params = { gasId, activeName, startTime: date[0], endTime: date[1], couponListJson, activeId }
          let tips = `活动将在${params.startTime}后开始生效，是否确认配置本次活动？`
          if (new Date(params.startTime).getTime() < new Date().getTime()) {
            tips = '活动配置完成后立刻生效，是否确认配置本次活动？'
          }
          this.$confirm(tips, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let res
            this.saveDisabled = true
            if (activeId) {
              res = await updateStoreCouponActive({ ...params })
            } else {
              res = await createStoreCouponActive({ ...params })
            }
            this.saveDisabled = false
            if (res.code !== 200) return
            this.$message.success('操作成功')
            this.$router.push({ path: '/marketCenter/marketActivity' })
          }).catch(() => {
          })
        } finally {
          this.saveDisabled = false
        }
      })
    },
    handelCheck (val) {
      if (val[val.length - 1] === '全部油品') {
        this.couponParams.oils = ['全部油品']
        this.checkDisabled = true
      } else {
        this.checkDisabled = false
      }
    },
    /**
     * 编辑优惠券
     */
    editAddCoupon (params, type) {
      this.couponParams = params ? { ...params, type } : { oils: [], numberLimit: false }
      this.checkDisabled = this.couponParams.oils.includes('全部油品')
      this.isShowEditAddCoupon = true
      this.$nextTick(() => {
        this.$refs.couponForm.clearValidate()
      })
    },
    saveCoupon () {
      this.$refs.couponForm.validate(valid => {
        if (!valid) return
        let result = this.couponParams
        const { onlyId, type, oils = [], couponMoney, couponConditionMoney } = result
        if (oils.length && oils.every(oil => oil.indexOf('全部油品') < 0)) {
          result.oilNames = oils.map(oil => {
            return this.oilTypeList.find(oilType => oil === `${oilType.id}`).oilNum
          }).join(',')
        } else {
          result.oilNames = '全部油品'
        }
        if (onlyId) {
          if (type) {
            this.couponList.forEach((item, index) => {
              onlyId === item.onlyId && this.$set(this.couponList, index, { ...result, onlyId: Date.now(), noSelect: false })
            })
          } else {
            this.selectedCoupon.forEach((item, index) => {
              onlyId === item.onlyId && this.$set(this.selectedCoupon, index, { ...result, onlyId: Date.now(), noSelect: true, isCanEdit: true })
            })
          }
        } else {
          const selectedLength = this.couponList.reduce((total, item) => total + !!item.checked, 0)
          result = Object.assign(result, {
            onlyId: Date.now(),
            isCanEdit: true,
            disabled: this.selectedCoupon.some(item => item.couponMoney === couponMoney && item.couponConditionMoney === couponConditionMoney) || (this.selectedCoupon.length + selectedLength) === 6
          })
          this.couponList.push({ ...result })
        }
        this.isShowEditAddCoupon = false
      })
    },
    /**
     * 删除优惠券
     */
    deleteCoupon (params, type) {
      this.$confirm('确定删除此券吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (type) {
          this.couponList = this.couponList.filter(item => item.onlyId !== params.onlyId)
        } else {
          this.selectedCoupon = this.selectedCoupon.filter(item => item.onlyId !== params.onlyId)
        }
      }).catch(() => {
      })
    },
    /**
     * 选择优惠券
     */
    showSelectCoupon () {
      const selectedLen = this.selectedCoupon.length
      this.couponList.forEach((coupon, index) => {
        const { couponMoney, couponConditionMoney } = coupon
        this.$set(this.couponList, index, {
          ...coupon,
          checked: false,
          disabled: this.selectedCoupon.some(item => item.couponMoney === couponMoney && item.couponConditionMoney === couponConditionMoney) || selectedLen === 6
        })
      })
      this.isShowSelectCoupon = true
    },
    selectCoupon (params) {
      // todo 优化逻辑
      const selectedLen = this.selectedCoupon.length
      this.couponList.forEach((coupon, index) => {
        if (coupon.onlyId === params.onlyId) {
          this.$set(this.couponList[index], 'checked', !params.checked)
        }
      })
      if (selectedLen + this.couponList.reduce((total, item) => total + !!item.checked, 0) === 6) {
        this.couponList.forEach((coupon, index) => {
          this.$set(this.couponList[index], 'disabled', this.selectedCoupon.some(item => item.couponMoney === coupon.couponMoney && item.couponConditionMoney === coupon.couponConditionMoney) || !coupon.checked)
        })
      } else {
        this.couponList.forEach((coupon, index) => {
          this.$set(this.couponList[index], 'disabled', this.selectedCoupon.some(item => item.couponMoney === coupon.couponMoney && item.couponConditionMoney === coupon.couponConditionMoney))
        })
      }
    },
    saveSelectedCoupon () {
      this.couponList.forEach(item => {
        item.checked && this.selectedCoupon.push({ ...item, noSelect: true, isCanEdit: true })
      })
      this.isShowSelectCoupon = false
    },
    /**
     * 获取油站、油号、优惠券模板
     */
    async getAllGasStationsApi () {
      try {
        const { code, result = [] } = await getAllGasInfoList()
        if (code !== 200) return
        const firstGasid = this.params.gasId || result[0].gasId
        this.$set(this.params, 'gasId', firstGasid)
        this.upGasId = firstGasid
        this.gasList = result
        this.searchGasApi(firstGasid)
      } catch (e) {
        console.log(e)
      }
    },
    async queryInterest (gasId) {
      try {
        const { code, result = 0 } = await queryInterest({ gasId, interestCode: 'coupon' })
        if (code !== 200) return
        this.interest = result
      } catch (e) {
        console.log(e)
      }
    },
    async searchGasApi (gasId) {
      if (this.upGasId !== gasId && this.selectedCoupon.length) {
        try {
          const isConfirm = await this.$confirm('切换油站后需要重新配置优惠券, 确认切换吗？', '确认提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          if (isConfirm !== 'confirm') {
            return this.$set(this.params, 'gasId', this.upGasId)
          }
          this.getCouponTemplate()
          this.selectedCoupon = []
          this.upGasId = gasId
        } catch (e) {
          this.$set(this.params, 'gasId', this.upGasId)
        }
      } else {
        this.upGasId = gasId
      }
      this.queryInterest(gasId)
      this.getDisabledDate(gasId)
      this.currGasName = this.gasList.find(gas => gas.gasId === gasId).gasName
      try {
        const { code, result = [] } = await searchGas({ gasId })
        if (code !== 200) return
        this.oilTypeList = result
      } catch (err) {
        console.log(err)
      }

    },
    async getCouponTemplate () {
      const { code, result = [] } = await getCouponTemplate()
      if (code !== 200) return
      this.couponList = result
      this.couponList.forEach((item, index) => {
        item.oils = ['全部油品']
        item.oilNames = '全部油品'
        item.onlyId = Date.now() + index
        item.numberLimit = false
        item.isCanEdit = true
      })
    },
    async getCouponLimit () {
      const res = await getCouponLimit()
      if (res.code !== 200) return
      this.couponRulesLimt = res.result
    },
    async getDisabledDate (gasId) {
      const { activeId = '' } = this.$route.query
      const res = await getDisabledDate({ activeId, gasId })
      if (res.code !== 200) return
      const { localDates = [] } = res.result
      this.disabledDate = localDates
    },
    getPlaceholder (type) {
      const { amount = {}, condition = {}, expire = {}, number = {} } = this.couponRulesLimt
      switch (type) {
        case 1:
          return `请输入${amount.min}-${amount.max}元优惠券面额`
        case 2:
          return `请输入${condition.min}-${condition.max}元使用门槛`
        case 3:
          return `请输入${expire.min}-${expire.max}天有效期`
        case 4:
          return `请输入${number.min}-${number.max}张限制`
      }
    }
  }
}
</script>

<style scoped lang="less">
  .box-wrapper {
    width: 100%;
    background: #fff;
    height: calc(100% - 10px);
    overflow-y: scroll;
    margin-top: 10px;
    padding-left: 15px;
    .title {
      font-size: 16px;
      font-weight: 800;
      color: #333333;
      margin: 25px 0;
      display: flex;
      align-items: flex-end;
      .text {
        font-size: 12px;
        font-weight: 400;
        color: #999999;
      }
      .tips {
        color: red;
      }
      img {
        width: 120px;
        height: 32px;
        margin: 0 5px;
        cursor: pointer;
      }
    }
    .el-form {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        width: 470px;
        /deep/ .el-date-editor, .el-select {
          width: 100%;
        }
        /deep/ .el-input-group__prepend {
          padding: 0 5px;
        }
        /deep/ .el-input-group__append {
          padding: 0 10px;
        }
      }
    }
    .coupon-box {
      display: flex;
      flex-wrap: wrap;
    }
  }

  .dialog-btns {
    text-align: center;
  }

  .input-radio {
    display: flex;
    .el-radio {
      display: flex;
      align-items: center;
    }
  }

  .dialog-header {
    text-align: center;
    position: relative;
    img {
      width: 120px;
      cursor: pointer;
      position: absolute;
      left: 0;
    }
    div {
      span {
        font-size: 13px;
        font-weight: 400;
        color: #999999;
        &:nth-child(1) {
          display: block;
          font-size: 18px;
          font-weight: 600;
          color: #222222;
          margin-bottom: 10px;
        }
      }
    }
  }

  .btns {
    text-align: center;
  }
</style>
